new Vue({
    el: '#app',
    data() {
        return {
            id: '',//挂牌单流水号
            ids: '',//交易单流水号
            type: '0',// 0: 挂牌方 1: 摘牌方
            formData: {},
            orderData: {},
            paystages: [],
            supply_order_logistics: {
                Quantity: 0,
            },// 发货
            payForm: {
                Amount: 0,
            },// 付款
            invoiceForm: {},//开票
            InvoiceView: [],//开票列表
            logistics_info: [],//物流
            dialogPayVisible: false, // 付款弹窗
            dialogCollectionVisible: false,// 收款弹窗
            dialogShipVisible: false, // 发货弹窗
            dialogReceiveVisible: false,//收货弹窗
            dialogInvoiceUploadVisible: false, // 开票弹窗
            dialogInvoiceViewVisible: false,// 收发票弹窗
            loading: false,// 节流
        }
    },
    beforeCreate() {
        function setRem() {
            const designWidth = 750; // 设计稿宽度（rpx）
            const maxWidth = 540; // 可选：限制最大宽度（如手机端常见值）
            const screenWidth = Math.min(window.innerWidth, maxWidth);
            const scale = screenWidth / designWidth;
            document.documentElement.style.fontSize = scale + 'px';
        }
        setRem();//1rem = 0.5px 对标小程序在 375px 宽的屏幕上，1rpx = 0.5px（因为 750rpx / 375px = 2）
    },
    mounted() {
        let URL = window.location.href;
        this.id = getQueryObject(URL, 'id');
        this.ids = getQueryObject(URL, 'ids');
        this.type = getQueryObject(URL, 'type');
        $('title').text(this.type == '0' ? '我的销售订单明细' : '我的采购明细');
        this.getLogistics();
        this.init();
    },
    computed: {
        stauts() {
            const { Contract_Status } = this.orderData;
            try {
                return this.type == '0' ? Contract_Status.charAt(0) : Contract_Status.charAt(1);
            } catch (error) {
                return '0';
            }

        }
    },
    methods: {
        async init(callback) {
            await Promise.allSettled([
                this.getList(),
                this.getOrder(),
                this.getPaystages()
            ]);
            callback ? callback() : null;
        },
        async getLogistics() {// 物流信息
            try {
                const data = await generalApi.generalQueryByTableName({
                    Data: 'logistics_info',
                    Condition: ''
                })
                this.logistics_info = data;
            } catch (error) {
                console.error(error);
            }
        },
        async getList() { // 挂牌信息
            try {
                const data = await generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 't_supply_hall',
                    Condition: utf8ToBase64(`%%,%%`),
                    ExtensionCondition: utf8ToBase64(`AND supply_unitprice.Supply_Unit_Price_SerialNumber='${this.id}'`)
                })
                if (data.length == 1) {
                    this.formData = data[0];
                }
            } catch (error) {
                console.error(error);
            }
        },
        async getOrder() { // 交易信息
            try {
                const data = await generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 't_supply_order',
                    Condition: utf8ToBase64(`%%,%%`),
                    ExtensionCondition: utf8ToBase64(`AND supply_order.Supply_Order_SerialNumber='${this.ids}'`)
                })
                if (data.length == 1) {
                    this.orderData = data[0];
                }
            } catch (error) {
                console.error(error);
            }
        },
        async getPaystages() { // 付款周期
            try {
                const data = await generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 'supply_payment_stages',
                    Condition: utf8ToBase64(this.ids),
                    ExtensionCondition: ''
                })
                this.paystages = data;
            } catch (error) {
                console.error(error);
            }
        },
        handleMoney(item) {
            if (this.type == '0') { // 挂牌方 收款
                this.payForm.maxAmount = Number(accSub(item.Paid_Amount, item.Collection_Amount));
                if (this.payForm.maxAmount == 0) {
                    this.$showToast({
                        title: '暂无可收款！'
                    })
                    return;
                }
                this.payForm.Supply_Order_SerialNumber = this.orderData.Supply_Order_SerialNumber;
                this.payForm.Supply_Order_Paystages_SerialNumber = item.Supply_Order_Paystages_SerialNumber;
                this.payForm.Trading_Amount = item.Trading_Amount;
                this.payForm.Paid_Amount = item.Paid_Amount;
                this.payForm.Remain_Amount = item.Remain_Amount;
                this.payForm.Collection_Amount = item.Collection_Amount;
                this.payForm.Unamount = item.Unamount;
                this.payForm.Amount = this.payForm.maxAmount;
                this.dialogCollectionVisible = true;
            } else { // 摘牌方 付款
                if (item.Remain_Amount == 0) {
                    this.$showToast({
                        title: '已完成付款！'
                    })
                    return;
                }
                this.payForm.Supply_Order_SerialNumber = this.orderData.Supply_Order_SerialNumber;
                this.payForm.Supply_Order_Paystages_SerialNumber = item.Supply_Order_Paystages_SerialNumber;
                this.payForm.Trading_Amount = item.Trading_Amount;
                this.payForm.Paid_Amount = item.Paid_Amount;
                this.payForm.Remain_Amount = item.Remain_Amount;
                this.payForm.Amount = Number(item.Remain_Amount);
                this.dialogPayVisible = true;
            }
        },
        async handleGoods(item) {
            if (this.type == '0') { // 挂牌方 发货
                if (this.orderData.Undelivery_Quantity == '0') {
                    this.$showToast({
                        title: '已完成发货！'
                    })
                    return;
                }
                this.supply_order_logistics.Supply_Order_SerialNumber = this.orderData.Supply_Order_SerialNumber;
                this.supply_order_logistics.Supply_Order_Paystages_SerialNumber = item.Supply_Order_Paystages_SerialNumber;
                this.dialogShipVisible = true;
            } else { // 摘牌方 收货
                if (this.orderData.Undelivery_Quantity == '0') {
                    this.$showToast({
                        title: '已完成收货！'
                    })
                    return;
                }
                try {
                    const data = await generalApi.generalQueryBySQLSerialNumber({
                        SQLSerialNumber: 'f_supply_order_logistics',
                        Condition: utf8ToBase64(this.ids),
                    })
                    if (data.length > 0) {
                        this.supply_order_logistics = { ...data[0], Quantity: Number(data[0].Delivery_Quantity) };
                        this.dialogReceiveVisible = true;
                    } else {
                        this.$showToast({
                            title: '对方暂未发货！'
                        })
                    }
                } catch (error) {
                    console.error(error);
                }
            }
        },
        async handleInvoice(item) {
            if (this.type == '0') { // 挂牌方 开票
                if (item.Collection_Amount == '0') {
                    this.$showToast({
                        title: '未确认收款，无法开票'
                    })
                    return;
                }
                this.invoiceForm.Supply_Order_Paystages_SerialNumber = item.Supply_Order_Paystages_SerialNumber;
                this.dialogInvoiceUploadVisible = true;
            } else { // 挂牌方 收票
                try {
                    const data = await generalApi.generalQueryByTableName({
                        Data: 'supply_order_invoice',
                        Condition: `Supply_Order_Paystages_SerialNumber='${item.Supply_Order_Paystages_SerialNumber}'`,
                    })
                    if (data.length > 0) {
                        this.InvoiceView = data;
                        this.dialogInvoiceViewVisible = true;
                    } else {
                        this.$showToast({
                            title: '对方暂未开票！'
                        })
                    }
                } catch (error) {
                    console.error(error);
                }
            }
        },
        handleExamine(str) {// 申请
            this.$showModal({
                title: '提示',
                content: '此操作将审核' + (str == '2' ? '通过' : '拒绝') + '，是否继续！',
                onConfirm: async () => {
                    try {
                        const data = await generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order',
                            Condition: `supply_order.Supply_Order_SerialNumber='${this.ids}'`
                        });
                        data[0].Row_Status = str;

                        let lJSONObject_DataSet = {
                            Modify: { supply_order: data }, Add: {}
                        };

                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '1', //客户端
                            Operation_Path: getRelativePath(),
                            Operation_Description: '挂牌方审核销售交易单',
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        const res = await generalApi.generalSaveByRequestBody({
                            Data: lJSONObject_DataSet
                        })
                        if (res.Status == "success") {
                            this.init();
                            this.$showToast({
                                title: '审核成功'
                            });
                        } else {
                            this.$showToast({
                                title: '审核失败，请重试！'
                            });
                        }
                    } catch (error) { }
                }
            })
        },
        handleContract() { // 确认合同
            this.$showModal({
                title: '提示',
                content: '此操作将确认合同，是否继续！',
                onConfirm: async () => {
                    try {
                        const data = await generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order',
                            Condition: `supply_order.Supply_Order_SerialNumber='${this.ids}'`
                        });

                        data[0].Contract_Status = (this.type == '0' ? (data[0].Contract_Status.charAt('0') + '1') : ('1' + data[0].Contract_Status.charAt('1')));

                        let lJSONObject_DataSet = {
                            Modify: { supply_order: data }, Add: {}
                        };
                        3
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '1', //客户端
                            Operation_Path: getRelativePath(),
                            Operation_Description: (this.type == '0' ? '挂牌方' : '摘牌方') + '确认合同',
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        const res = await generalApi.generalSaveByRequestBody({
                            Data: lJSONObject_DataSet
                        })
                        if (res.Status == "success") {
                            this.init();
                            this.$showToast({
                                title: '确认合同成功'
                            });
                        } else {
                            this.$showToast({
                                title: '确认合同失败，请重试！'
                            });
                        }
                    } catch (error) { }
                }
            })
        },
        async submitPay() { // 付款
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                try {
                    const { payForm } = this;
                    const [res1, res2] = await Promise.allSettled([
                        generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order_paystages',
                            Condition: `supply_order_paystages.Supply_Order_Paystages_SerialNumber='${payForm.Supply_Order_Paystages_SerialNumber}'`
                        }),
                        generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order',
                            Condition: `supply_order.Supply_Order_SerialNumber='${payForm.Supply_Order_SerialNumber}'`
                        })
                    ]);

                    const supply_order_paystages = res1.status == 'fulfilled' ? res1.value : [];
                    const supply_order = res2.status == 'fulfilled' ? res2.value : [];

                    supply_order[0].Paid_Amount = accAdd(supply_order[0].Paid_Amount, payForm.Amount);
                    supply_order[0].Remain_Amount = accSub(supply_order[0].Remain_Amount, payForm.Amount);

                    supply_order_paystages[0].Paid_Amount = accAdd(supply_order_paystages[0].Paid_Amount, payForm.Amount);
                    supply_order_paystages[0].Remain_Amount = accSub(supply_order_paystages[0].Remain_Amount, payForm.Amount);

                    let lJSONObject_DataSet = {
                        Modify: { supply_order, supply_order_paystages },
                        Add: {
                            payment: [{
                                Supplier_SerialNumber: this.formData.Enterprise_Info_SerialNumber,
                                Payment_Date: getYMDHMSDate(),
                                Payment_Amount: payForm.Amount,
                                Bank_Voucher_SerialNumber: '',
                                Enterprise_Info_SerialNumber: getCookie('enterprise'),
                                Children: {
                                    payment_detail: [{
                                        Business_Order_SerialNumber: payForm.Supply_Order_Paystages_SerialNumber,
                                        Payment_Method: '电子汇款',
                                        Payment_Type: '0',
                                        Amount: payForm.Amount,
                                        Enterprise_Info_SerialNumber: getCookie('enterprise')
                                    }],
                                    payment_voucher: [{
                                        Payment_Voucher_Picture: payForm.Picture_URL,
                                        Enterprise_Info_SerialNumber: getCookie('enterprise')
                                    }]
                                }
                            }]
                        }
                    };

                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '1', //客户端
                        Operation_Path: getRelativePath(),
                        Operation_Description: '买方付款',
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
                    const res = await generalApi.generalSaveByRequestBody({
                        Data: lJSONObject_DataSet
                    })
                    if (res.Status == "success") {
                        this.payForm = { Amount: 0 };
                        this.dialogPayVisible = false;
                        this.init();
                        this.$showToast({
                            title: '付款成功'
                        });
                    } else {
                        this.$showToast({
                            title: '付款失败，请重试！'
                        });
                    }

                } catch (error) {
                    console.error(error)
                }
                this.loading = false;
            }
        },
        async submitCollection() { // 收款
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                try {
                    const { payForm } = this;
                    // 查询
                    const [res1, res2] = await Promise.allSettled([
                        generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order_paystages',
                            Condition: `supply_order_paystages.Supply_Order_Paystages_SerialNumber='${payForm.Supply_Order_Paystages_SerialNumber}'`
                        }),
                        generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order',
                            Condition: `supply_order.Supply_Order_SerialNumber='${payForm.Supply_Order_SerialNumber}'`
                        })
                    ]);

                    const supply_order_paystages = res1.status == 'fulfilled' ? res1.value : [];
                    const supply_order = res2.status == 'fulfilled' ? res2.value : [];

                    // 修改
                    supply_order[0].Collection_Amount = accAdd(supply_order[0].Collection_Amount, payForm.Amount);
                    supply_order[0].Unamount = accSub(supply_order[0].Unamount, payForm.Amount);

                    supply_order_paystages[0].Collection_Amount = accAdd(supply_order_paystages[0].Collection_Amount, payForm.Amount);
                    supply_order_paystages[0].Unamount = accSub(supply_order_paystages[0].Unamount, payForm.Amount);

                    // 组合
                    let lJSONObject_DataSet = {
                        Modify: { supply_order_paystages, supply_order },
                        Add: {
                            collection: [{
                                Order_Type: '2',
                                Sales_Date: '',
                                Collection_Date: getYMDHMSDate(),
                                Sales_Amount: payForm.Amount,
                                Collection_Amount: payForm.Amount,
                                Enterprise_Info_SerialNumber: getCookie('enterprise'),
                                Children: {
                                    collection_detail: [{
                                        Collection_Order_Number: payForm.Supply_Order_Paystages_SerialNumber,
                                        Collection_Type: '7',
                                        Amount: payForm.Amount,
                                        Enterprise_Info_SerialNumber: getCookie('enterprise'),
                                    }]
                                }
                            }]
                        }
                    };

                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '1', //客户端
                        Operation_Path: getRelativePath(),
                        Operation_Description: '卖方收款',
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
                    const res = await generalApi.generalSaveByRequestBody({
                        Data: lJSONObject_DataSet
                    })
                    if (res.Status == "success") {
                        this.payForm = {
                            Amount: 0,
                        };
                        this.dialogCollectionVisible = false;
                        this.init();
                        this.$showToast({
                            title: '收款成功'
                        });
                    } else {
                        this.$showToast({
                            title: '收款失败，请重试！'
                        });
                    }
                } catch (error) {
                    console.error(error)
                }
                this.loading = false;
            }
        },
        async submitLogistics() { // 发货
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                try {
                    const [res1, res2] = await Promise.allSettled([
                        generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order_paystages',
                            Condition: `supply_order_paystages.Supply_Order_Paystages_SerialNumber='${this.supply_order_logistics.Supply_Order_Paystages_SerialNumber}'`
                        }),
                        generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order',
                            Condition: `supply_order.Supply_Order_SerialNumber='${this.supply_order_logistics.Supply_Order_SerialNumber}'`
                        })
                    ]);

                    const supply_order_paystages = res1.status == 'fulfilled' ? res1.value : [];
                    const supply_order = res2.status == 'fulfilled' ? res2.value : [];

                    supply_order[0].Delivery_Quantity = accAdd(supply_order[0].Delivery_Quantity, supply_order[0].Quantity);
                    supply_order[0].Undelivery_Quantity = accSub(supply_order[0].Undelivery_Quantity, supply_order[0].Quantity);

                    this.supply_order_logistics.Delivery_Data = getYMDHMSDate();
                    this.supply_order_logistics.Delivery_Quantity = supply_order[0].Quantity;
                    this.supply_order_logistics.Enterprise_Info_SerialNumber = getCookie('enterprise');

                    const supply_order_logistics = [this.supply_order_logistics];

                    let lJSONObject_DataSet = {
                        Modify: { supply_order, supply_order_paystages }, Add: { supply_order_logistics }
                    };

                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '1', //客户端
                        Operation_Path: getRelativePath(),
                        Operation_Description: '卖家发货',
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]

                    const res = await generalApi.generalSaveByRequestBody({
                        Data: lJSONObject_DataSet
                    })

                    if (res.Status == "success") {
                        this.supply_order_logistics = {};
                        this.dialogShipVisible = false;
                        this.init();
                        this.$showToast({
                            title: '发货成功'
                        });
                    } else {
                        this.$showToast({
                            title: '发货失败，请重试！'
                        });
                    }
                } catch (error) {
                    console.error(error)
                }
                this.loading = false;
            }
        },
        async submitInvoiceUpload() { // 开票
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                try { 
                    let lJSONObject_DataSet = {
                        Add: {
                            supply_order_invoice: [{
                                Supply_Order_SerialNumber: this.orderData.Supply_Order_SerialNumber,
                                Supply_Order_Paystages_SerialNumber: this.invoiceForm.Supply_Order_Paystages_SerialNumber,
                                Picture_URL: this.invoiceForm.Picture_URL,
                                Enterprise_Info_SerialNumber: getCookie('enterprise')
                            }]
                        }
                    };
                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '1', //客户端
                        Operation_Path: getRelativePath(),
                        Operation_Description: '卖家开票',
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
    
                    const res = await generalApi.generalSaveByRequestBody({
                        Data: lJSONObject_DataSet
                    })
    
                    if (res.Status == "success") {
                        this.invoiceForm = {};
                        this.dialogInvoiceUploadVisible = false;
                        this.init();
                        this.$showToast({
                            title: '开票成功'
                        });
                    } else {
                        this.$showToast({
                            title: '开票失败，请重试！'
                        });
                    }
                } catch (error) {
                    console.error(error)
                }
                this.loading = false;
            }
        },
        async submitReceive() { // 确认收货
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                try {
                    const { supply_order_logistics } = this;
                    const supply_order = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_order',
                        Condition: `supply_order.Supply_Order_SerialNumber='${supply_order_logistics.Supply_Order_SerialNumber}'`
                    })

                    supply_order[0].Receipt_Quantity = supply_order_logistics.Quantity;// 已收货
                    supply_order[0].Unreceipt_Quantity = accSub(supply_order[0].Unreceipt_Quantity, supply_order_logistics.Quantity); // 未收货

                    let lJSONObject_DataSet = {
                        Modify: { supply_order },
                        Add: {
                            sales_receipt: [{
                                Receipt_Date: getYMDHMSDate(),
                                Receipt_Type: '0',
                                Store_SerialNumber: '',
                                Enterprise_Info_SerialNumber: getCookie('enterprise'),
                                Children: {
                                    sales_receipt_detail: [{
                                        Order_Type: '0',
                                        Sales_Order_SerialNumber: supply_order_logistics.Supply_Order_SerialNumber,
                                        // Article_SerialNumber: 
                                        Enterprise_Info_SerialNumber: getCookie('enterprise'),
                                    }]
                                }
                            }]
                        }
                    };

                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '1', //客户端
                        Operation_Path: getRelativePath(),
                        Operation_Description: '买家收货',
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]

                    const res = await generalApi.generalSaveByRequestBody({
                        Data: lJSONObject_DataSet
                    })

                    if (res.Status == "success") {
                        this.supply_order_logistics = {};
                        this.dialogReceiveVisible = false;
                        this.init();
                        this.$showToast({
                            title: '收货成功'
                        });
                    } else {
                        this.$showToast({
                            title: '收货失败，请重试！'
                        });
                    }
                } catch (error) {
                    console.error(error);
                }
                this.loading = false;
            }
        },
        async download(row) { // 下载发票
            let apiUrl = imageApi + row.Picture_URL;
            let fileName = apiUrl.split('/').pop();

            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        preview(index) { //预览发票
            this.$refs['previewInvoice'][index].clickHandler();
        },
        async validateAllForms() { //校验方法
            //获取当前页面上所有的Elform
            let forms = [];
            for (let key in this.$refs) {
                const ref = this.$refs[key];
                if (ref.$options && ref.$options.name == 'ElForm') {
                    forms.push(ref);
                }
            }
            //判断每个Elform的校验是否通过
            let isfail = false;
            for (const form of forms) {
                try {
                    await form.validate();
                } catch (error) {
                    isfail = true;
                }
            }
            if (isfail) {
                return false;
            }
            return true;
        },
    },
})
